package net.shouyong.topbilliards.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;

import net.shouyong.topbilliards.Main2Activity;
import net.shouyong.topbilliards.R;
import net.shouyong.topbilliards.bean.BilliardRecord;
import net.shouyong.topbilliards.bean.BilliardRecordContent;
import net.shouyong.topbilliards.bean.CompareBilliardRecord;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * A fragment representing a data of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class HomeFragment extends Fragment implements BillirdrecordRecyclerViewAdapter.Action {

    private static final String ARG_COLUMN_COUNT = "column-count";
    private int mColumnCount = 1;
    private OnListFragmentInteractionListener mListener;

    private final int REFRESH_TIME = 5 * 1000;//5s
    private final int MSG_UPDATE = 10001;
    private List<? extends  BilliardRecord> data = null;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE:
                    post(runnable);
                    sendEmptyMessageDelayed(MSG_UPDATE, REFRESH_TIME);
                    break;
            }
        }
    };
//    private RecyclerView recyclerView;
    private Main2Activity mainActivity;

    private final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (data == null) {
                return;
            }
            for (BilliardRecord billiardRecord : data) {
                if (billiardRecord.isStart()) {
                    billiardRecord.getCost();//updata cost
                }
            }
            if (getRecyclerView() != null) {
                getRecyclerView().getAdapter().notifyDataSetChanged();
            }

            BilliardRecord.saveAllInBackground(data);//save to server.

            if (mListener != null) {
                mListener.updateTodayTotalCost(null);
            }
        }
    };

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public HomeFragment() {

    }

    @SuppressWarnings("unused")
    public static HomeFragment newInstance(int columnCount) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainActivity = (Main2Activity) getActivity();

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }

        initData();
    }

    private void initData() {
        AVQuery<BilliardRecord> query = AVObject.getQuery(BilliardRecord.class);
        query.whereDoesNotExist(BilliardRecord.END_TIME);
        query.findInBackground(new FindCallback<BilliardRecord>() {
            @Override
            public void done(List<BilliardRecord> list, AVException e) {
                // list 返回的就是有图片的 Todo 集合
                mainActivity.hideProgressBar();

                if (e != null || list.isEmpty()) {
                    data = null;
                    e.printStackTrace();
                    if (getRecyclerView() != null) {
                        getRecyclerView().setAdapter(new BillirdrecordRecyclerViewAdapter(BilliardRecordContent.ITEMS, HomeFragment.this));
                    }
                    return;
                }
//                data = list;
                if (getRecyclerView() == null) {
//                    getRecyclerView().setAdapter(new BillirdrecordRecyclerViewAdapter(BilliardRecordContent.ITEMS, mListener));
                    return;
                }
                if (list != null && !list.isEmpty()) {


                    for (BilliardRecord record : list) {
                        Log.e("tag",record.getObjectId());
                    }

                    List<BilliardRecord> list1 = organizeData(list, -1);
                    for (BilliardRecord record : list1) {
                        Log.e("tag1",record.getObjectId());
                    }
                    list.removeAll(list1);

                    for (BilliardRecord record : list) {
                        Log.e("tag_ori",record.getObjectId());
                    }


                    BilliardRecord.deleteAllInBackground(list, new DeleteCallback() {
                        @Override
                        public void done(AVException e) {

                        }
                    });


                    data = list1;
                    getRecyclerView().setAdapter(new BillirdrecordRecyclerViewAdapter(list1, HomeFragment.this));
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_billirdrecord_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            RecyclerView recyclerView = (RecyclerView) view;
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }
            data = data == null ?BilliardRecordContent.ITEMS : data;
            recyclerView.setAdapter(new BillirdrecordRecyclerViewAdapter(data, this));
        }

        mHandler.sendEmptyMessageDelayed(MSG_UPDATE, REFRESH_TIME);

        return view;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnListFragmentInteractionListener");
        }
    }

    public RecyclerView getRecyclerView() {
        return (RecyclerView)getView();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void start(BillirdrecordRecyclerViewAdapter.ViewHolder viewHolder) {
        mHandler.sendEmptyMessage(MSG_UPDATE);
    }

    /**
     *
     * 1、去除结束的台球桌号,保存到服务器
     * 2、添加新的台球记录到列表中去。
     *
     * @param list  需要整理的原始数据
     * @param index 结束的台球桌号。-1为无效值。
     * @return
     */
    private List<BilliardRecord> organizeData(List<? extends  BilliardRecord> list, int index) {
        /**
         * 用于验证数据有效性。
         * 1,去重
         * 2，key只能是 1，2，3，4
         * 3，并且keys.length == 4
         */
        Map<Integer, BilliardRecord> maps = new HashMap<>();
        for (BilliardRecord record : list) {
            if (record.getIndex() == index ) {
                record.saveInBackground();
                continue;
            }
            maps.put(record.getIndex(), record);
        }
        if (maps.keySet().size() < 4) {
            if (!maps.containsKey(1)) {
                //15
                maps.put(1, BilliardRecordContent.createDummyItem(1, 15));
            }

            if (!maps.containsKey(2)) {
                //15
                maps.put(2, BilliardRecordContent.createDummyItem(2, 15));
            }
            if (!maps.containsKey(3)) {
                //10
                maps.put(3, BilliardRecordContent.createDummyItem(3, 10));
            }
            if (!maps.containsKey(4)) {
                //10
                maps.put(4, BilliardRecordContent.createDummyItem(4, 10));
            }
        } else if (maps.keySet().size() == 4) {

        }

        List<BilliardRecord> list1 = new ArrayList<>(maps.values());
        Collections.sort(list1, new CompareBilliardRecord());

        return list1;
    }


    @Override
    public void stop(BillirdrecordRecyclerViewAdapter.ViewHolder viewHolder) {
        this.data = organizeData(data, viewHolder.mItem.getIndex());
        getRecyclerView().setAdapter(new BillirdrecordRecyclerViewAdapter(data, this));
        mHandler.sendEmptyMessage(MSG_UPDATE);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnListFragmentInteractionListener {
        void onListFragmentInteraction(BilliardRecord item);

        void updateTodayTotalCost(String date);
    }
}
